package com.gap.dam.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.gap.dam.common.login.RequestTokenBO;
import com.gap.dam.util.RequestTokenUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    private static final String CREATE_BY = "createBy";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_BY = "updateBy";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(CREATE_TIME)) {
            Object createTime = this.getFieldValByName(CREATE_TIME, metaObject);
            if (createTime == null) {
                this.strictInsertFill(metaObject, CREATE_TIME, Date.class, new Date());
            }
        }

        if (metaObject.hasSetter(CREATE_BY)) {
            Object createBy = this.getFieldValByName(CREATE_BY, metaObject);
            if (createBy == null) {
                RequestTokenBO requestTokenBO = RequestTokenUtil.getRequestUser();
                if (requestTokenBO != null
                        && requestTokenBO.getRequestUserId() != null) {
                    this.strictInsertFill(metaObject, CREATE_BY, Integer.class, requestTokenBO.getRequestUserId());
                }
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE_TIME)) {
            Object createTime = this.getFieldValByName(UPDATE_TIME, metaObject);
            if (createTime == null) {
                this.strictInsertFill(metaObject, UPDATE_TIME, Date.class, new Date());
            }
        }

        if (metaObject.hasSetter(UPDATE_BY)) {
            Object createBy = this.getFieldValByName(UPDATE_BY, metaObject);
            if (createBy == null) {
                RequestTokenBO requestTokenBO = RequestTokenUtil.getRequestUser();
                if (requestTokenBO != null
                        && requestTokenBO.getRequestUserId() != null) {
                    this.strictInsertFill(metaObject, UPDATE_BY, Integer.class, requestTokenBO.getRequestUserId());
                }
            }
        }
    }
}
